import mmcv
import inspect
import numpy as np
from mmcv.utils import deprecated_api_warning, is_tuple_of
from numpy import random
import imgaug.augmenters as iaa
from imgaug.augmenters import Sequential
from imgaug.augmentables.segmaps import SegmentationMapsOnImage
from imgaug.augmentables.polys import Polygon, PolygonsOnImage
from mmdet.datasets.builder import PIPELINES
import copy
import uuid
import cv2
import os
@PIPELINES.register_module()
class Imageaug(object):
    def __init__(self, transforms,):
        self.transforms = transforms
        st = lambda aug: iaa.Sometimes(0.5, aug)
        self.aug = Sequential([st(self.albu_builder(t)) for t in self.transforms],random_order=True)


    def albu_builder(self, cfg):
        """Import a module from albumentations.

        It inherits some of :func:`build_from_cfg` logic.
        Args:
            cfg (dict): Config dict. It should at least contain the key "type".
        Returns:
            obj: The constructed object.
        """

        assert isinstance(cfg, dict) and 'type' in cfg
        args = cfg.copy()

        obj_type = args.pop('type')
        if mmcv.is_str(obj_type):
            obj_cls = getattr(iaa, obj_type)
        elif inspect.isclass(obj_type):
            obj_cls = obj_type
        else:
            raise TypeError(
                f'type must be a str or valid type, but got {type(obj_type)}')

        if 'transforms' in args:
            args['transforms'] = [
                self.albu_builder(transform)
                for transform in args['transforms']
            ]

        return obj_cls(**args)



    def __call__(self, results):
        imgs_aug= self.aug(image=results['img'])
        results['img'] = imgs_aug
        results['img_shape'] = imgs_aug.shape
        return results

    def __repr__(self):
        repr_str = self.__class__.__name__ + f'(transforms={self.transforms})'
        return repr_str

